package com.dcits.mvc.common.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

import org.apache.commons.io.IOUtils;

import com.dcits.mvc.common.model.FileInfo;
import com.jfinal.kit.PathKit;

public class FileInfoService {
	
	private static final FileInfo dao = new FileInfo().dao();
	
	public void save(FileInfo info) {
		info.save();
	}
	
	public List<FileInfo> listAll(Integer configId, String host, String tags) {
		String sql = "select * from " + FileInfo.TABLE_NAME + " where " 
				+ FileInfo.column_server_infos + " like ? and " +  FileInfo.column_server_infos
				+ " like ?";
		return dao.find(sql, "%" + host + "%", "%" + tags + "%");
	}
	
	public boolean del(Integer fileId) {
		return dao.deleteById(fileId);
	}
	
	public FileInfo get(Integer fileId) {
		return dao.findById(fileId);
	}
	
	public String getFileInfo(Integer fileId) throws Exception {
		FileInfo file = get(fileId);
		if (file == null) {
			throw new Exception("该记录不存在!");
		}
		File f = new File(PathKit.getWebRootPath() + "/" + file.getFilePath());
		if (!f.exists()) {
			throw new Exception("该文件已被删除,无法查看详细信息!");
		}
		
		//读取文件内容并返回给前台
		List<String> strs = null;
		try {
			strs = IOUtils.readLines(new FileInputStream(f), "UTF-8");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			throw new IOException("读取文件信息错误!");
		}
		
		return strs.get(0);
	}
}
